package leetcode;

/**
 * Reverse digits of an integer.
 * Example1: x = 123, return 321
 * Example2: x = -123, return -321
 * Created by hao on 17-3-15.
 */
public class ReverseInteger {
    private static int reverse(int x) {
        if (Math.abs(x) < 10 && x != Integer.MIN_VALUE) {
            return x;
        }
        char[] numChars = String.valueOf(x).toCharArray();
        int begin = x < 0 ? 1 : 0;
        int end = numChars.length - 1;
        char temp;
        while (end > begin) {
            temp = numChars[begin];
            numChars[begin] = numChars[end];
            numChars[end] = temp;
            begin++;
            end--;
        }
        long result = Long.parseLong(new String(numChars));
        return result > Integer.MAX_VALUE || result < Integer.MIN_VALUE ? 0 : (int) result;
    }

    public static void main(String[] args) {
        int result = reverse(-2147483648);
        System.out.println(result);
        result = reverse(-21483648);
        System.out.println(result);
        result = reverse(-10);
        System.out.println(result);
    }
}
